package com.nexttwist.dao;

import java.util.ArrayList;
import java.util.List;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;

import com.nexttwist.model.SampleTrack;

public class TrackDAO {
	
	// Database fields
	private SQLiteDatabase database;
	private SqlLiteHelper dbHelper;

	private String[] allColumns = { "trackId", "trackUrl", "title", "album", "vote", "userId" };

	public TrackDAO(Context context) {
		dbHelper = new SqlLiteHelper(context);
	}

	public void open() throws SQLException {
		database = dbHelper.getWritableDatabase();
	}

	public void close() {
		dbHelper.close();
	}

	public SampleTrack createTrack(SampleTrack track) {
		ContentValues values = new ContentValues();
		
		values.put("trackUrl", track.getTrackUrl());
		values.put("title", track.getTitle());
		values.put("album", track.getAlbum());
		values.put("vote", track.getTrackUrl());
		values.put("userId", track.getUserId());

		database.insert(SqlLiteHelper.TABLE_TRACK, null, values);
		
		return track;
	}

	public void deleteTrack(SampleTrack track) {
		long id = track.getTrackId();
		System.out.println("Comment deleted with id: " + id);
		database.delete(SqlLiteHelper.TABLE_TRACK, "trackId = " + id, null);
	}

	public List<SampleTrack> getAllTracks() {
		List<SampleTrack> tracks = new ArrayList<SampleTrack>();

		Cursor cursor = database.query(SqlLiteHelper.TABLE_TRACK, allColumns, null, null, null, null, null);
		cursor.moveToFirst();
		
		while (!cursor.isAfterLast()) {
			SampleTrack tract = cursorToTrack(cursor);
			tracks.add(tract);
			cursor.moveToNext();
		}
		// make sure to close the cursor
		cursor.close();
		return tracks;
	}

	private SampleTrack cursorToTrack(Cursor cursor) {
		SampleTrack track = new SampleTrack();
		track.setTrackId(cursor.getInt(0));
		track.setTrackUrl(cursor.getString(1));
		track.setTitle(cursor.getString(2));
		track.setAlbum(cursor.getString(3));
		track.setUserId(cursor.getInt(4));
		return track;
	}
}
